<template>
  <a-card>
    <template #title>
      <a-form layout="vertical">
        <a-row :gutter="16">
          <a-col class="gutter-row" :span="6">
            <a-form-item :label="$t('角色名称')">
              <a-select v-model:value="page.rid" allowClear>
                <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">{{
                    item.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="6">
            <a-form-item :label="$t('账号')">
              <a-input v-model:value="page.account"/>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="6">
            <a-form-item :label="$t('员工姓名')">
              <a-input v-model:value="page.name"/>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="6">
            <a-form-item :label="$t('状态')">
              <a-select v-model:value="page.status" allowClear
                        :options="[{label:$t('启用'),value:1},{label:$t('禁用'),value:0}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <a-button type="primary" @click="addStaff">{{ $t('添加员工') }}</a-button>
    </div>
    <a-table row-key="id" :columns="tableColumn" :pagination="pagination" :data-source="tableData" :scroll="{x:1000}">
      <template #operation="{record }">
        <a-button type="link" @click="editStaff(record)">{{ $t('编辑') }}</a-button>
        <a-button type="link" @click="resetPasswordConfirm(record)">{{ $t('重置密码') }}</a-button>
        <a-button type="link" @click="bindGoogleSecret(record)">{{ $t('重绑谷歌验证器') }}</a-button>
      </template>
      <template #status="{record }">
        <a-switch :checked="record.status === 1" @change="changeStatus(record)"></a-switch>
      </template>
    </a-table>
    <a-modal v-model:visible="visible.isShow" :title="visible.title" :afterClose="clearForm" @ok="staffConfirm"
             :confirm-loading="confirmLoading"
             :maskClosable="false">
      <a-form :rules="staffRulesForm" :model="staffForm" ref="formRef" :label-col="{span:4}">
        <a-form-item :label="$t('员工姓名')" name="name">
          <a-input v-model:value="staffForm.name"/>
        </a-form-item>
        <a-form-item :label="$t('账号')" name="account">
          <a-input v-model:value="staffForm.account" :disabled="visible.type === 'edit'"/>
        </a-form-item>
        <a-form-item :label="$t('邮箱')" name="email">
          <a-input v-model:value="staffForm.email"/>
        </a-form-item>
        <a-form-item :label="$t('电话')">
          <a-input v-model:value="staffForm.phone"/>
        </a-form-item>
        <a-form-item :label="$t('选择角色')" name="rid" v-show="visible.type === 'add'">
          <a-select v-model:value="staffForm.rid">
            <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('备注')">
          <a-textarea :rows="4" v-model:value="staffForm.remark"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import {reactive, ref, toRefs, onMounted, computed, h} from 'vue'
import i18n from "../../../locale";
import {
  fetchStaffList,
  increaseStaff,
  updateStaff,
  staffUpdateStatus,
  resetPassword,
  fetchRoleTypeList,
} from "../../../api/authority";
import {getResetGoogleSecretLink} from "../../../api/index"
import {message, Modal, Button} from "ant-design-vue";

const $t = i18n.global.t
const tableColumn = [
  {title: $t('员工姓名'), dataIndex: 'name', width: 150, align: 'center'},
  {title: $t('账号'), dataIndex: 'account', width: 100, align: 'center'},
  {title: $t('邮箱'), dataIndex: 'email', width: 100, align: 'center'},
  {title: $t('电话'), dataIndex: 'phone', width: 100, align: 'center'},
  {title: $t('角色名称'), dataIndex: 'roleName', width: 100, align: 'center'},
  {title: $t('备注'), dataIndex: 'remark', width: 200, align: 'center'},
  {title: $t('状态'), dataIndex: 'status', width: 100, align: 'center', slots: {customRender: 'status',}},
  {title: $t('创建时间'), dataIndex: 'creationTime', width: 150, align: 'center'},
  {title: $t('操作'), width: 150, align: 'center', fixed: 'right', slots: {customRender: 'operation',}},
]
export default {
  name: "StaffManage",
  setup() {
    const formRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      visible: {
        isShow: false,
        type: '',
        title: ''
      },
      staffForm: {},
      staffRulesForm: {
        name: [
          {required: true, message: $t('不能为空'), trigger: 'blur'},
        ],
        account: [
          {required: true, message: $t('不能为空'), trigger: 'blur'},
        ],
        email: [
          {required: true, message: $t('不能为空'), trigger: 'blur'},
        ],
        rid: [
          {required: true, message: $t('不能为空'), trigger: 'change', type: 'number'},
        ],
      },
      confirmLoading: false,
      tableData: [],
      roleList: []
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + $t('条'),
      onChange: (page) => {
        state.page.pageNum = page
        method.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        method.getTableData()
      }
    }))
    const method = {
      async getTableData() {
        const res = await fetchStaffList(state.page)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
        }
      },
      async getRoleList() {
        const res = await fetchRoleTypeList({merchantId: 1})
        if (res.code === 200) {
          state.roleList = res.data.filter(item => item.id !== 2)
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        method.getTableData()
      },
      clearForm() {
        state.staffForm = {}
        formRef.value.resetFields()
      },
      resetPasswordConfirm({systemUserId}) {
        Modal.confirm({
          title: $t('确认重置密码') + '?',
          async onOk() {
            const res = await resetPassword({systemUserId})
            if (res.code === 200) {
              message.success($t('操作成功'))
              method.getTableData()
            }
          },
        });
      },
      addStaff() {
        state.visible = {
          isShow: true,
          type: 'add',
          title: $t('添加员工')
        }

      },
      editStaff(rows) {
        state.visible = {
          isShow: true,
          type: 'edit',
          title: $t('编辑员工')
        }
        state.staffForm = {...rows}
      },
      staffConfirm() {
        formRef.value.validate().then(async () => {
          state.confirmLoading = true
          const api = ((params) => state.visible.type === 'add' ? increaseStaff(params) : updateStaff(params))
          const res = await api(state.staffForm)
          if (res.code === 200) {
            state.visible.isShow = false
            message.success(state.visible.type === 'add' ? $t('添加成功') : $t('编辑成功'))
            method.getTableData()
          }
          state.confirmLoading = false
        })
      },
      changeStatus({systemUserId, status}) {
        Modal.confirm({
          title: $t('确认进行此操作') + '?',
          async onOk() {
            const res = await staffUpdateStatus({id: systemUserId, status: status === 1 ? 0 : 1})
            if (res.code === 200) {
              message.success($t('操作成功'))
              method.getTableData()
            }
          },
        });
      },
      async bindGoogleSecret(row) {
        const res = await getResetGoogleSecretLink({adminUserId: row.systemUserId})
        if (res.code === 200) {
          Modal.confirm({
            okText: '复制链接',
            content: h('div', {
              style: {
                fontSize: '14px'
              }
            }, '重绑链接:', h('span', {
              style: {
                color: '#1890ff',
              },
            }, res.data)),
            onOk: () => {
              let input = document.createElement("input");
              input.value = res.data || ''
              document.body.appendChild(input);
              input.select()
              document.execCommand('copy')
              message.success($t('复制成功'))
              document.body.removeChild(input);
            }
          });
        }

      }
    }
    onMounted(() => {
      method.getTableData()
      method.getRoleList()
    })
    return {
      tableColumn,
      formRef,
      pagination,
      ...method,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
